package cn.mrlong.base.view

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import cn.mrlong.base.bean.MessageType
import cn.mrlong.base.utils.LoadingObserver
import cn.mrlong.base.utils.SnackbarUtils
import cn.mrlong.base.utils.ToastUtil
import com.afollestad.materialdialogs.MaterialDialog

open abstract class BaseFragment<T : ViewDataBinding> : Fragment() {

    abstract val layoutId: Int
    lateinit var binding: T

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, layoutId, container, false)
        binding.lifecycleOwner = this
        return binding.root
    }

    fun showToast(message: String) {
        activity?.let { ToastUtil.show(it.applicationContext, message) }
    }

    /**
     *
     * @param vm BaseViewModel
     * @param toastViewRoot View?
     */
    fun initMessage(vm: BaseViewModel, toastViewRoot: View?) {
        //通知
        vm.noticeMessage.observe(this, Observer {
            it.run {
                if (MessageType.TOAST == it.title) {
                    if (null == toastViewRoot) {
                        throw RuntimeException("Snackbar must has root view ")
                    }
                    SnackbarUtils.show(toastViewRoot, it.content.toString())
                } else if (MessageType.DIALOG == it.title) {
                    MaterialDialog(activity as Context)
                        .show {
                            title(text = "提示")
                            message(text = it.content.toString())
                            positiveButton(text = "确定")
                        }
                }
            }
        })
        vm.progressBarState.observe(this, LoadingObserver(activity as Context, "加载中..."))
    }
}